<template>
  <div class="change-password">
    <h3>重置密码</h3>
    <el-form ref="form" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="原密码" prop="old_pwd">
        <el-input v-model="form.old_pwd" placeholder="请输入原密码" />
      </el-form-item>
      <el-form-item label="新密码" prop="new_pwd">
        <el-input type="password" v-model="form.new_pwd" placeholder="请输入新密码" />
      </el-form-item>
      <el-form-item label="确认新密码" prop="re_pwd">
        <el-input type="password" v-model="form.re_pwd" placeholder="请再次输入新密码" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">修改密码</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { editPassword } from '@/api/user'
export default {
  data () {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.form.re_pwd !== '') {
          this.$refs.ruleForm.validateField('re_pwd')
        }
        callback()
      }
    }
    const validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.form.new_pwd) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      form: {
        old_pwd: '', // 旧密码
        new_pwd: '', // 新密码
        re_pwd: '' // 确认新密码
      },
      rules: {
        old_pwd: [
          { required: true, message: '请输入原密码', trigger: 'blur' }
        ],
        new_pwd: [
          { validator: validatePass, required: true, trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        re_pwd: [
          { validator: validatePass2, required: true, trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 重置表单
    reset () {
      this.$refs.form.resetFields()
    },
    // 提交表单
    async submit () {
      if (this.new_pwd !== this.re_pwd) return
      await editPassword(this.form)
      // 弹窗
      this.$message.success('修改成功')
    }
  }
}
</script>

<style lang="less" scoped>
.change-password {
  h3 {
    padding: 50px;
  }
  .el-input {
    width: 500px;
  }
}
</style>
